package cn.zxh.csdn_maven.base.pojo;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.log4j.Logger;

import cn.zxh.csdn_maven.base.util.StringUtil;
import cn.zxh.csdn_maven.base.util.File.PropertiesUtil;
import cn.zxh.csdn_maven.base.util.File.ReadFromFile;
import cn.zxh.csdn_maven.base.util.File.WriteToFile;

/**
 * 管理网站的cookie
 * @author zhangxinhua
 *
 */
public class Cookies {

	private static Logger logger = Logger.getLogger(Cookies.class);
	private static String isForce=PropertiesUtil.getValueFromPropertiesKey("base.properties", "forceUpdate").toString();
	private static String cookie_path = PropertiesUtil.getValueFromPropertiesKey("base.properties", "cookie_path").toString();
	/**cookie字符串*/
	private static StringBuffer cookies=new StringBuffer("");
	public static String getCookies(){
		if("".equals(cookies.toString())){
			List<String> readFileByLines = ReadFromFile.readFileByLines(cookie_path);
			for (String string : readFileByLines) {
				cookies.append(string);
			}
		}
		return cookies.toString();
	}
	public static void setCookies(List<String> list){
		if(null==list){
			return;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		for (String cookieStr : list) {
			if(cookieStr.indexOf("=")==-1){
				continue;
			}
			List<String> cookieList = StringUtil.getListFromStrBySeparatorChars(cookieStr, "=");
			map.put(cookieList.get(0), cookieList.get(1));
		}
		setCookies(map);
	}
	public static void setCookies(Map<String, Object> map){
		if(map==null||map.size()<1){
			logger.info("cookie is empty");
			return;
		}
		for (Entry<String, Object> entry : map.entrySet()) {
			String key = entry.getKey();
			/**不需要更新已存在的key*/
			if(!"lastest".equals(isForce)&&!"undefined".equals(getCookie(key))){
				continue;
			}
			/**如果key已存在则更新*/
			if(!"undefined".equals(getCookie(key))){
				/**存在删除*/
				delCookie(key);
			}
			/**重新加入*/
			cookies.append(entry.getKey()+"="+entry.getValue()+";");
		}
		wirte();
		logger.info("lastest cookies："+cookies);
	}
	/**
	 * 添加cookie
	 * @param headers
	 */
	public static void setCookies(Header[] headers){
		Map<String, Object> map = new HashMap<String, Object>();
		if(headers==null||headers.length<1){
			logger.info("Cookies is empty");
			return ;
		}
		for (Header header : headers) {
			String str = header.toString();
			if(str.contains(":")){
				str=str.split(":")[1];
				if(str.contains(";")){
					str=str.split(";")[0]+";";
				}
			}
			String[] split = str.split("=");
			map.put(split[0].trim(),split[1].substring(0,split[1].length()-1));
			//cookies.append(str);
		}
		setCookies(map);
//		wirte();
//		logger.info("lastest cookies："+cookies);
	}
	
	/**
	 * 验证cookie中是否包含某个key
	 */
	public static String getCookie(String key){
		String value="undefined";
		String cookiesStr = cookies.toString();
		String[] cookiesArray = cookiesStr.split(";");
		for (String cookie : cookiesArray) {
			String[] keyAndValue = cookie.split("=");
			if(key.equals(keyAndValue[0].trim())){
				value=keyAndValue[1];
				break;
			}
		}
		return value;
	}
	
	/**
	 * 删除key
	 */
	public static boolean delCookie(String key){
		boolean flag=false;
		String cookiesStr = cookies.toString();
		String[] cookiesArray = cookiesStr.split(";");
		for (String cookie : cookiesArray) {
			String[] keyAndValue = cookie.split("=");
			if(key.equals(keyAndValue[0].trim())){
				int index=cookiesStr.indexOf(cookie);
				cookies.delete(index, index+cookie.length()+1);
				flag=true;
//				break;
			}
		}
		return flag;
	}
	private static void wirte(){
		try {
			/**写入*/
			WriteToFile.writeByOutputStreamWrite(PropertiesUtil.getValueFromPropertiesKey("base.properties", "cookie_path").toString(), cookies.toString().trim());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
